package com.java.example.util.loader

import android.content.Context
import android.view.Gravity
import androidx.appcompat.app.AppCompatDialog
import com.java.example.R
import com.java.example.util.DimenUtil.screenWidth
import com.java.example.util.loader.LoaderCreator.create

object LatteLoader {
    //宽高缩放比
    private const val LOADER_SIZE_SCALE = 8

    //高度偏移量
    private const val LOADER_OFFSET_SCALE = 10

    private val LOADERS = ArrayList<AppCompatDialog>()

    private val DEFAULT_LOADER = LoaderStyle.BallClipRotatePulseIndicator.name

    @JvmStatic
    fun showLoading(context: Context?, type: Enum<LoaderStyle>) {
        showLoading(context, type.name)
    }

    /**
     * 默认的loading
     *
     * @param context
     */
    @JvmOverloads
    fun showLoading(context: Context?, type: String? = DEFAULT_LOADER) {
        if (context == null) return
        val dialog = AppCompatDialog(context, R.style.dialog)

        val avLoadingIndicatorView = create(type!!, context)

        dialog.setContentView(avLoadingIndicatorView)
        //不允许外部点击消失
        dialog.setCanceledOnTouchOutside(false)

        val deviceHeight = screenWidth
        val deviceWidth = screenWidth

        val dialogWindow = dialog.window
        if (dialogWindow != null) {
            val lp = dialogWindow.attributes
            lp.width = deviceWidth / LOADER_SIZE_SCALE
            lp.height = deviceHeight / LOADER_SIZE_SCALE
            lp.height = lp.height + deviceHeight / LOADER_OFFSET_SCALE
            lp.gravity = Gravity.CENTER
        }
        LOADERS.add(dialog)
        dialog.show()
    }

    @JvmStatic
    fun stopLoading() {
        for (dialog in LOADERS) {
            if (dialog != null) {
                if (dialog.isShowing) {
                    dialog.cancel()
                }
            }
        }
    }
}
